<?php
/**
 * Created by PhpStorm.
 * User: 户学
 * Date: 2018/5/18
 * Time: 14:09
 */

class Order extends M_Controller
{
    public function index(){
        list($data, $total, $param)	= $this->_limit_page(); // 数据库中分页查询
        $id = (int)$param['id'];
        $this->load->library('dip');
//      print_r($this->_limit_page());exit;
        $this->template->assign(array(
            'list'=>$data,
            'total' => $total,
            'param' => $param,
            'auser' => $this->db->where('id', $id)->get('course_order')->row_array(),
            'pages'	=> $this->get_pagination(dr_url('admin/order/index', array(
                'uid' => $id,
                'total' => $total,
                'search' => IS_POST ? 1 : $this->input->get('search')
            )), $total)
        ));
        $this->template->display('order/index.html');
    }
    public function add(){

        if(IS_POST){
            $data = $this->input->get_post('data');
            if(empty($data['mobile'])){
                $this->admin_msg('手机号码不能为空');
            }
            if(empty($data['name'])){
                $this->admin_msg('姓名不能为空');
            }
            $order = array();
            $order['mobile'] = $data['mobile'];
            $order['name'] = $data['name'];
            $order['course_name'] = $data['course_name'];
            $order['remark'] = $data['remark'];
            //生成订单逻辑
            $order_no = time().rand(100000,999999);
            $order['order_no'] = $order_no;
            $order['addtime'] = time();
            $order['source'] = '后台录入';

            $this->db->insert("course_order",$order);
            $id = $this->db->insert_id();
            $course = array();
            $totalprice = 0;
            // 处理订单-课程逻辑
            if(!empty($data['course'])){
                $arr = explode("#",$data['course']);
                if(count($arr)>0){
                    foreach($arr as $key=> $cour){
                        $cou = explode(',',$cour);
                        if(count($cou)>0){
                            foreach ($cou as $k=> $couree){
                                if($k == 0){
                                    if(!empty($couree)){
                                        $course[$key]['stage'] = $couree;
                                    }
                                }else if($k == 1){
                                    if(!empty($couree)) {
                                        $course[$key]['subject'] = $couree;
                                    }
                                }else if($k == 2){
                                    if(!empty($couree)) {
                                        $course[$key]['type'] = $couree;
                                    }
                                }else if($k == 3){
                                    if(!empty($couree)) {
                                        $course[$key]['price'] = $couree;
                                    }
                                }else if($k == 4){
                                    if(!empty($couree)) {
                                        $course[$key]['num'] = $couree;
                                    }
                                }
                                if($course[$key]['price'] && $course[$key]['num']){
                                    $course[$key]['totalprice'] = $course[$key]['price']*$course[$key]['num'];
                                    $totalprice += $course[$key]['totalprice'];
                                    $course[$key]['order_id'] = $id;
                                }
                            }
                        }
                    }
                    //添加订单课程内容
                    $result = $this->db->insert_batch('order_course', $course);
                    if($result){
                        //更新订单总金额
                        $this->db->where('id',$id)->update("course_order",array("totalprice"=>$totalprice));
                        $this->admin_msg('添加订单成功', dr_url(APP_DIR.'/'.$this->router->class.'/index', $this->post_param), 1);
                    }
                }
            }else{
                $this->admin_msg("提交数据不能为空");
            }

        }
        $this->template->assign(
            array(
                'name'=>'录入订单',
                'stages'=>array("学前","小学","初中","高中"),
                'subjects'=>array("语文","数学","英语","物理","化学","生物","政治","历史","地理"),
                'types'=>array("1v4","1v1","免费试听","公开课","专题课"),
            )
        );
        $this->template->display('order/course_add.html');

    }
    //关闭订单
    public function close(){
        $oid = $this->input->get_post('oid');
        $order = $this->db->where('id',$oid)->get('course_order')->row_array();
        if(empty($order)){
            $this->msg("订单不存在");
        }
        if($order['status'] != 0){
            $this->msg("订单在该状态下不能删除");
        }
        $result = $this->db->where('id',$oid)->update('course_order',array('status'=>4));
        if($result){
            $this->admin_msg('关闭订单成功', dr_url(APP_DIR.'/'.$this->router->class.'/index', $this->post_param), 1);
        }

    }
    //删除订单
    public function del(){
        $oid = $this->input->get_post('oid');
        $order = $this->db->where('id',$oid)->get('course_order')->row_array();
        if(empty($order)){
            $this->msg("订单不存在");
        }
//        print_r($this->post_param);exit;
        if($order['status'] != 4){
            $this->msg("订单在该状态下不能删除");
        }
        $result = $this->db->where('id',$oid)->update('course_order',array('is_del'=>0));
        if($result){
            $this->admin_msg('删除订单成功', dr_url(APP_DIR.'/'.$this->router->class.'/index', $this->post_param), 1);
        }


    }
    public function detail(){
        $oid = $this->input->get_post('oid');
        $data = $this->db->where('id',$oid)->get('course_order')->row_array();
        !$data && exit(fc_lang('对不起，订单数据被删除或者查询不存在'));
        $course = $this->db->where('order_id',$oid)->get('order_course')->result_array();
        if(empty($course)){
            exit(fc_lang('对不起，课程数据被删除或者查询不存在'));
        }
        $this->template->assign(array(
                'order'=>$data,
                'course'=>$course,
                'name'=>'订单详情',
                'totalprice'=>$data['totalprice']
            )
        );
        $this->template->display('order/order_detail.html');
    }
    public function pay(){
        $oid = $this->input->get_post('oid');
        $order = $this->db->where('id',$oid)->get("course_order")->row_array();
        require_once dirname(dirname(dirname(dirname(dirname((__FILE__))))))."/".'/api/linepay/weixin/lib/WxPay.Api.php';
        require_once dirname(dirname(dirname(dirname(dirname((__FILE__))))))."/".'/api/linepay/weixin/example/WxPay.NativePay.php';
        require_once  dirname(dirname(dirname(dirname(dirname((__FILE__))))))."/".'api/linepay/weixin/example/log.php';
        $notify = new NativePay();

        $input = new WxPayUnifiedOrder();
        $input->SetBody("test");
        $input->SetAttach("test");
//        $input->SetOut_trade_no(WxPayConfig::MCHID.date("YmdHis"));
        $input->SetOut_trade_no($order['order_no']);
        $input->SetTotal_fee($order['totalprice']*100);
//        $input->SetTotal_fee('1');
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
//        $input->SetNotify_url("http://paysdk.weixin.qq.com/example/notify.php");
//        $input->SetNotify_url("http://47.100.228.50/api/linepay/weixin/example/notify.php");
        $input->SetNotify_url(SITE_DOMAIN."/api/linepay/weixin/example/notify.php");
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id("123456789");
        $result = $notify->GetPayUrl($input);
        $url2 = $result["code_url"];


        $this->template->assign(array(
            "oid"=>$oid,
            "url"=>$url2
        ));
        $this->template->display("order/pay.html");
    }
    //支付宝支付
    public function zfbpay(){
        error_reporting(E_ALL);
        require_once dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/api/linepay/zfb/config.php';
        require_once dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/api/linepay/zfb/pagepay/service/AlipayTradeService.php';
        require_once dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/api/linepay/zfb/pagepay/buildermodel/AlipayTradePagePayContentBuilder.php';
//        $config = dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/api/linepay/zfb/config.php';
        $oid = $this->input->get_post('oid');
        $order = $this->db->where('id',$oid)->get("course_order")->row_array();
        //商户订单号，商户网站订单系统中唯一订单号，必填
//        $out_trade_no = trim($_POST['WIDout_trade_no']);
        $out_trade_no = $order['order_no'];

        //订单名称，必填
//        $subject = trim($_POST['WIDsubject']);
        $subject = "购买课程";

        //付款金额，必填
//        $total_amount = trim($_POST['WIDtotal_amount']);
//        $total_amount = "0.01";
        $total_amount = $order['totalprice'];

        //商品描述，可空
//        $body = trim($_POST['WIDbody']);
        $body ="k12课程";

        //构造参数
        $payRequestBuilder = new AlipayTradePagePayContentBuilder();
        $payRequestBuilder->setBody($body);
        $payRequestBuilder->setSubject($subject);
        $payRequestBuilder->setTotalAmount($total_amount);
        $payRequestBuilder->setOutTradeNo($out_trade_no);

        $aop = new AlipayTradeService($config);

        /**
         * pagePay 电脑网站支付请求
         * @param $builder 业务参数，使用buildmodel中的对象生成。
         * @param $return_url 同步跳转地址，公网可以访问
         * @param $notify_url 异步通知地址，公网可以访问
         * @return $response 支付宝返回的信息
         */
        $response = $aop->pagePay($payRequestBuilder,$config['return_url'],$config['notify_url']);

        //输出表单
        var_dump($response);
    }
    //获取订单状态
    public function orderStatus(){
       $oid  = $this->input->get_post('oid');
       $order = $this->db->select('status')->where('id',$oid)->get('course_order')->row_array();
        $arr = array();
       if(!empty($order)){
           if($order['status']){
            $arr['status'] = 1;
            $arr['msg'] = '订单已经支付成功,3秒后即将跳转';
           }else{
               $arr['status'] = 0;
               $arr['msg'] = '订单未支付';
           }
           echo json_encode($arr);exit;
       }else{
           $arr['status'] = -1;
           $arr['msg'] = '订单不存在';
       }
        echo json_encode($arr);exit;
    }
    //库分期退款
    public function payback(){
        $oid  = $this->input->get_post("oid");
        $order = $this->db->select('order_no,status,mobile')->where('id',$oid)->get('course_order')->row_array();
        if(empty($order)){
            $this->msg("订单不存在获取已经删除");
        }
        //通过手机号码去查下用户
        $user = $this->db->select('id')->where('mobile',$order['mobile'])->get('user')->row_array();
        $data = array(
            "orderId"=>$order['order_no'],
            "applyId"=>'47521',
            "refundAmount"=>600,
            "reson"=>'错误转款',
        );
        $risk = array(
            "deviceType"=>equipType('pc'),
            'ip'=> $_SERVER['REMOTE_ADDR'],
        );
        $param = array(
            "uid"=>$user['id'],
            "midTransaction"=>midPlatform,
            "opType"=>3001,
            "time"=>microtime(true)*1000,
            "data"=>$data,
            "risk"=>$risk
        );

        $json = json_encode($param);
        $this->load->library("secooCrypt");
        $encryptObj = new SecooCrypt();
        $result = $encryptObj->requestEncrypt(AEC_KEY,MD5_KEY,midPlatform,VERSION,$json);//加密结果
        $res = cur_post(KU_FENG_QI_URL,$result);
        $obj = json_decode($res,true);;
        $resultJson = "{\"sign\":\"".$obj['sign']."\",\"data\":\"".$obj['data']."\"}";
        $m = $encryptObj->responseDecrypt(AEC_KEY,MD5_KEY,$resultJson);//解密结果
        $resObj = json_decode($m,true);
        if($resObj['result'] == 200){
            $this->msg("退款成功");
        }else{
            $this->msg('退款失败');
        }
    }
//    //修改订单状态
//    public function modifyOrderStatus(){
//        $sign = $this->input->get_post('sign');
//        $order_no = $this->input->get_post('order_no');
//        $pay_type = $this->input->get_post('pay_type');
//        if(!empty($sign) && $sign == 'SD45645sdfmlsdfjusd12132snxnzchaqllqaqwqweqewq45dvs'){
//            $paytype = 0;
//            if($pay_type == 'zfb'){
//                $paytype = 1;
//            }else if($pay_type == 'wx'){
//                $paytype = 2;
//            }
//            $this->db->where('order_no',$order_no)->update('course_order',array('pay_type'=>$paytype,'status'=>1));
//        }
//    }

    private function _where(&$select) {

        $uid = (int)$this->input->get('id');
        $uid = $uid ? $uid : $this->uid;
        $search = $this->input->get('search');
        $cache_file = md5($this->duri->uri(1).$uid.$this->uid.SITE_ID.$this->input->ip_address().$this->input->user_agent()); // 缓存文件名称

        // 存在POST提交时，重新生成缓存文件
        if (IS_POST) {
            $data = $this->input->post('data');
            $this->cache->file->save($cache_file, $data, 3600);
            $search = 1;
            unset($_GET['page']);
        }
//        $select->where('id', $uid);
        $select->where('is_del', 1);
        // 存在search参数时，读取缓存文件
        if ($search == 1) {
            $data = $this->cache->file->get($cache_file);
            if (isset($data['start']) && $data['start'] && $data['start'] != $data['end']) {
                $data['end'] = $data['end'] ? $data['end'] : SYS_TIME;
                $select->where('logintime BETWEEN '.$data['start'].' AND '. $data['end']);
            }
        }
        $data['id'] = $uid;
        return $data;
    }

    private function  _limit_page(){
        $page = max((int)$this->input->get_post('page'),1);
        $_total = (int)$this->input->get_post('total');

        if(!$_total){
//            $_total = $this->db->count_all_results('course_order');
            $count = $this->db->select("count(*) as count")->where("is_del",1)->get('course_order')->row_array();
            $_total = $count['count'];
//            if(!$_total){
////                return array(array(), 0 ,$_param);
//                return array();
//            }
        }

        $select = $this->db;
        $_param = $this->_where($select);
        $result = $this->db
            ->limit(SITE_ADMIN_PAGESIZE, SITE_ADMIN_PAGESIZE * ($page - 1))
            ->order_by('id desc')
            ->get('course_order')
            ->result_array();
        return array($result,$_total, $_param);
    }

}